import { useRef, useState, useEffect } from "react";
import "./App.css";
import VideoComponent from "./components/videoComponent";
import videoOption from "@/components/videoComponent/option.ts";
import { videos } from "@/utils/videoList";
import { Button } from "antd";

function App() {
  const playerRef = useRef(null);
  const [videoIndex, setVideoIndex] = useState(0); //视频列表下标
  const handlePlayerReady = (player: any) => {
    playerRef.current = player;
    player.src(videos[videoIndex]);
    player.on("waiting", () => {
      console.log(`%c waiting`, `color:red`);
    });
    player.on("dispose", () => {
      console.log(`%c dispose`, `color:blue`);
    });
    player.on("play", () => {
      console.log(`%c play`, `color:blue`);
    });
    player.on("pause", () => {
      console.log(`%c 视频暂停`, `color:blue`);
    });
    player.on("ended", () => {
      console.log("视频播放完成");
    });
    player.on("canplay", () => {
      console.log(`%c canplay`, `color:blue`);
    });
  };
  const nextVideo = () => {
    if (videoIndex + 1 >= videos.length) {
      console.log("没有更多视频了");
      return;
    }
    setVideoIndex(videoIndex + 1);
  };
  const preVideo = () => {
    if (videoIndex - 1 < 0) {
      console.log("已经是第一条了");
      return;
    }
    setVideoIndex(videoIndex - 1);
  };
  const func = (e: any) => {
    const { keyCode } = e;
    if (keyCode === 38) {
      //上键
      preVideo();
    } else if (keyCode === 40) {
      //下键
      nextVideo();
    }
    console.log(`当前的index:${videoIndex};video:${videos}`);
  };
  useEffect(() => {
    document.addEventListener("keyup", func);
    return () => {
      document.removeEventListener("keyup", func);
    };
  }, [videoIndex]);
  const playBtn = () => {
    playerRef.current && playerRef.current.play();
  };
  return (
    <div>
      <VideoComponent
        options={{ ...videoOption }}
        src={videos[videoIndex]}
        onReady={handlePlayerReady}
      ></VideoComponent>
      <Button style={{}} onClick={playBtn}>
        播放
      </Button>
    </div>
  );
}

export default App;
